<?php
/**
 * Created by PhpStorm.
 * userValidate: hms
 * Date: 2018/8/7
 * Time: 9:27
 */

namespace app\mini\controller;

use think\Controller;
use think\Config;
use redis\Redis;
use think\Db;
use think\Request;
use think\Session;
use app\mini\model\Member;
use app\Tools\VerifyCodeImage;
use app\mini\model\LotteryPrize;
use app\mini\model\LotteryOrder;
use app\mini\model\Order;

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: https://test.com');

class Lottery extends Controller
{

    private $appId = 'wxa85cd2ff38f1b9a3';
    private $appSecret = '2f5dd8579ea172459312fcebc9607541';

    private $betResult = 11;

    private $day1 = '2020-01-25';
    private $day2 = '2020-01-26';
    private $day3 = '2020-01-27';
    private $day4 = '2020-01-28';
    private $day5 = '2020-01-29';
    private $day6 = '2020-01-30';
    private $day7 = '2020-01-31';

    /**
     * 登录
     * @param Request $request
     * @param app\api\model\User $user
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function login(Request $request, Member $user, Order $order) {
        $param = $request->param();
        $redis = Redis::instance();
//        if (Session::has('code')) {
//            $code = Session::get('code');
//            if (strtolower($code) == strtolower(trim($param['code']))) {
                if ($param['mobile'] && $param['password']) {
                    $where['mobile'] = ['eq', trim($param['mobile'])];
                    $user_info = $user->getUserInfo($where);
                    if ($user_info) {
                        $password = md5(trim($param['password']));
                        if ($password == $user_info['password'] || $user_info['password'] == md5($password) || password_verify($param['password'],$user_info['password'])) {
                            $auth = $this->loginBefore($user_info);//登录额外判断
                            //$this->lotteryNum($user_info['id']);
//                            $this->loginBefore($user_info);//登录额外判断
//                            $this->lotteryNum($user_info['id']); //抽奖相关
                            Db::startTrans();
                            try {
                                $token = accessToken();
                                $oldToken = $redis->get('lottery_user:' . $user_info['id']);
                                if (!empty($user_info['token']))
                                    $redis->hDel('lottery_user_info', $oldToken);
                                $user_info['login_time'] = time();
                                $user_info['lottery_token'] = $token;
                                $user_info['is_vip'] = empty($auth)?2:1;
                                $redis->hSet('lottery_user_info', $token, json_encode($user_info));
                                $redis->set('lottery_user_auth:' . $user_info['id'], $token,86400);
                                //春节活动用户总积分
//                                $isFirst = $this->lotteryNewYear($user_info['id'],$user_info['is_vip']);
//                                if($user_info['is_vip'] == 1 && !empty($isFirst)){
//                                    $isAdd = 1;
//                                }else{
//                                    $isAdd = 0;
//                                }
                                $money = $redis->get('lottery_user_money:' . $user_info['id']);
                                if($money === false){
                                    $redis->set('lottery_user_money:' . $user_info['id'], 0);
                                }

                                Session('user_id', $user_info['id']);
                                Session('token', $token);
//                                Session::delete('code');
                                Db::commit();
                                $redis->set('lottery_user:' . $user_info['id'], $token);
                                $result = Config::get('code.success');
                                $result['token'] = $token;
                                $result['is_vip'] = $user_info['is_vip'];
//                                $result['is_add'] = $isAdd;
                            } catch (\Exception $e) {
                                Db::rollback();
                                return $e->getMessage();
                            }
                        } else {
                            $result['msg'] = '密码错误';
                            $result['status'] = 203;
                        }
                    } else {
                        $result['msg'] = '您尚未注册，请联系推荐人';
                        $result['status'] = 203;
                    }
                } else {
                    $result = Config::set('code.mistake');
                }
//            } else {
//                $result = Config::get('code.codeFail');
//            }
//        } else {
//            $result = Config::get('code.codeEmpty');
//        }
        return json($result);
    }

    /*
     * vip首登奖励
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    private function lotteryNewYear($user_id,$isVip){
        $redis = Redis::instance();
        $row = $redis->get('lottery_vip_user_login:'. $user_id);
        if($row === false){
            $money = $redis->get('lottery_user_money:' . $user_id);
            $money = empty($money)?0:$money;
            if($isVip == 1){
                $redis->set('lottery_user_money:' . $user_id, $money+100);
                $redis->set('lottery_vip_user_login:'. $user_id,100);
                $redis->set('lottery_vip_user_login_time:'. $user_id,date('Y-m-d H:i:s'));
                return true;
            }else{
                $redis->set('lottery_user_money:' . $user_id, $money);
            }
            return false;
        }else{
            return false;
        }
    }

    /*
     * 抽奖次数判定
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    private function lotteryNum($user_id){
        $redis = Redis::instance();
        $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_id);
//        if($row <= 0 && $row !== false){
//            $result = Config::get('code.error');
//            $result['msg'] = '今日抽奖次数已用完';
//            echo json_encode($result);die;
//        }
        if($row === false){
            $redis->set('lottery_user:' . date('Y-m-d') . $user_id, 3);
            $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_id);
        }
        return $row;
    }

    /*
     * 登录额外判断
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    private function loginBefore($user_info)
    {
        $redis = Redis::instance();
        $order = new Order();
        $where['uid'] = ['eq', $user_info['id']];
        $where['status'] = ['>', 1];
        $where['project_id'] = ['in' , [46,50]];
        $orderMoney = $order->selectInfo($where,'sum(money)');
        $where['project_id'] = ['in' , [37,44]];
        $orderMoney1 = $order->selectInfo($where,'sum(money)');
        $where['project_id'] = ['in' , [51,53]];
        $orderMoney2 = $order->selectInfo($where,'sum(money)');
        if ($orderMoney[0]['sum(money)'] >= 30000 || $orderMoney1[0]['sum(money)'] >= 10000 || $orderMoney2[0]['sum(money)'] >= 10000) {
            $redis->set('lottery_vip:'.date('Y-m-d H:i:s').'/'.$user_info['id'],$user_info['id'].'/'.date('Y-m-d H:i:s'));
            return true;
//            abort(json([
//                'msg' => '您目前不满足VIP条件，请联系好融艺官方客服了解如何成为《被光抓走的人》VIP',
//                'status' => 222
//            ]));
        }else{
            $redis->set('lottery_no_vip:'.date('Y-m-d H:i:s').'/'.$user_info['id'],$user_info['id'].'/'.date('Y-m-d H:i:s'));
            return false;
        }
    }

    /*
     * 获取图形验证码
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function getPicCode(Request $request)
    {
        $code = createRandomNum(4);
        Session('code',$code);
        $imageCode = new VerifyCodeImage(80,20,$code);
        $file = $imageCode->show();
        $result = Config::get('code.success');
        $result['code'] = $file;
        return json($result);
    }

    /*
     * 抽奖活动
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function active(Request $request,Order $order)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;
        if(empty($user_info)){
            return json(Config::get('code.emptyToken'));
        }
        if(time() < strtotime('2019-11-8 11:0:0')){
        //if(time() < strtotime('2019-9-30 14:0:0')){
            $result = Config::get('code.error');
            $result['msg'] = '活动尚未开始，请查看游戏规则';
        }elseif(strtotime('2019-11-8 11:0:0') < time() && time() < strtotime('2019-11-10 23:59:58')) {
        //elseif(strtotime('2019-9-30 14:0:0') < time() && time() < strtotime('2019-11-30 14:08:0')) {
            $res = $this->lotteryAction($user_info,4);
            $redis->set('lottery_of_batch4:' . date('Y-m-d H:i:s', time()) . "/" . $user_info['id'] ,$user_info['id'] . "/" . date('Y-m-d H:i:s', time()));
            return $res;
        }else{
            $result = Config::get('code.error');
            $result['msg'] = '活动已结束，感谢您的参与';
        }
        return json($result);
    }

    //模拟抽奖高频率多次
//    public function getLottery()
//    {
//        set_time_limit(0);
//        $lotteryPrize = new LotteryPrize();
//        $lotteryOrder = new LotteryOrder();
//        $user_info['id'] = 1;
//        $user_info['mobile'] = '15708497348';
//        $barch = 3;
//        $res = [];
//        for ($i = 0; $i < 3000; $i++) {
//            $where['batch'] = ['eq',$barch];
//            $where['num'] = ['>',0];
//            $prize = $lotteryPrize->selectAllInfo($where,'id,v');
//            if(count($prize) == 1){
//                var_dump($i);
//                var_dump($res);
//                halt($row);
//            }
//            $rid = $this->lottery($prize);
//            Db::startTrans();
//            try {
//                $lotteryPrize->where('id',$rid)->setDec('num',1);  //减数量
//                Db::commit();
//                $res[$rid] += 1;
//                if($i > 2000){
//                    $row[$i] = $rid;
//                }
//            } catch (\Exception $e) {
//                Db::rollback();
//                return $e->getMessage();
//                $result = Config::get('code.error');
//            }
//        }
//        var_dump($res);
//        halt($row);
//    }


    /*
     * 抽奖活动操作动作
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function lotteryAction($user_info,$barch){
        $lotteryPrize = new LotteryPrize();
        $lotteryOrder = new LotteryOrder();
        $owhere['batch'] = ['eq',$barch];
        $owhere['member_id'] = ['eq',$user_info['id']];
        $winning = $lotteryOrder->getInfo($owhere,'id');
        if(!empty($winning['id'])){
            $this->judgeNum($user_info['id']);
            $result = Config::get('code.success');
            if($barch == 4){
                $result['data'] = ['id' => 28,'name' => '谢谢参与'];
            }else{
                $result = Config::get('code.error');
            }
            return json($result);
        }
        $where['batch'] = ['eq',$barch];
        $where['num'] = ['>',0];
        $prize = $lotteryPrize->selectAllInfo($where,'*');
        $rid = $this->lottery($prize);
        if($rid == 28 || $rid == 30){
            $this->judgeNum($user_info['id']);
            $result = Config::get('code.success');
            if($barch == 4){
                $result['data'] = ['id' => 30,'name' => '谢谢参与'];
            }else{
                $result = Config::get('code.error');
            }
            return json($result);
        }
        Db::startTrans();
        try {
            $where['id'] = ['eq',$rid];
            $isPrize = $lotteryPrize->getInfo($where,'id,name,num'); //在检测一下奖品数量是否>0,主要应对高并发情况;
            if(empty($isPrize)){
                return json(Config::get('code.null'));
            }
            $this->judgeNum($user_info['id']);
            if($isPrize['num'] <= 0){
                $result = Config::get('code.success');
                if($barch == 4){
                    $result['data'] = ['id' => 28,'name' => '谢谢参与'];
                }else{
                    $result = Config::get('code.error');
                }
                return json($result);
            }
            $data = [
                'member_id' => $user_info['id'],
                'mobile' => $user_info['mobile'],
                'prize_id' => $rid,
                'code' => generateRandomString(6),
                'batch' => $barch,
            ];
            $lotteryOrder->save($data); //生成订单
            $lotteryPrize->where('id',$rid)->setDec('num',1);  //减数量
            Db::commit();
            $result = Config::get('code.success');
            $result['data'] = ['id' => $isPrize['id'],'name' => $isPrize['name']];
            return json($result);
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
            $result = Config::get('code.error');
        }
    }

    /*
     * 抽奖次数判断
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function judgeNum($user_id){
        $redis = Redis::instance();
        $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_id);
        if($row <= 0 && $row !== false){
            $result = Config::get('code.error');
            $result['msg'] = '今日抽奖次数已用完';
            echo json_encode($result);die;
        }
        if(empty($row)){
            $redis->set('lottery_user:' . date('Y-m-d') . $user_id, 3);
            $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_id);
        }
        $redis->set('lottery_user:' . date('Y-m-d') . $user_id, $row-1);
        return $row;
    }

    /*
     * 转发抽奖次数增加
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function forwardAddNum(){
        $request = request();
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;
        $forward = $redis->get('forward:' . date('Y-m-d', time()) . "/" . $user_info['id'] );
        if($forward === false){
            $redis->set('forward:' . date('Y-m-d', time()) . "/" . $user_info['id'] ,$user_info['id'] . "/" . date('Y-m-d H:i:s', time()));
            $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_info['id']);
            if($row === false){
                $redis->set('lottery_user:' . date('Y-m-d') . $user_info['id'], 3);
                $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_info['id']);
            }
            $redis->set('lottery_user:' . date('Y-m-d') . $user_info['id'], $row+1);
            $result = Config::get('code.success');
            $result['msg'] = '您的抽奖次数已增加';
        }else{
            $result = Config::get('code.error');
            $result['msg'] = '您今日的抽奖已增加，请明日再来';
        }
        return json($result);
    }

    /*
     * 抽奖前置动作
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function beforeLottery(){
        $request = request();
        $redis = Redis::instance();
        $token = $request->header('token');
        if ($token) {
            $user_info = json_decode($redis->hGet('lottery_user_info' , $token) ,true);
            if ($user_info) {
                $status = Session::get('user_id');
                if(empty($status)){
                    abort(json([
                        'msg' => '账号异常请重新登录',
                        'status' => 202
                    ]));
                }
                $auth = $redis->get('lottery_user_auth:' . $user_info['id']);
                if(empty($auth)){
                    abort(json([
                        'msg' => '账号过期请重新登录!',
                        'status' => 202
                    ]));
                }
                $request->lottery_user_info = $user_info;
            }else{
                abort(json([
                    'msg' => '账号异常请重新登录',
                    'status' => 202
                ]));
            }
        } else {
            abort(json([
                'msg' => '请登录',
                'status' => 202
            ]));
        }
    }

    /*
     * 抽奖奖品与剩余次数
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function alGetPrize(Request $request,LotteryOrder $lotteryOrder){
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;
        if(empty($user_info)){
            return json(Config::get('code.emptyToken'));
        }
        $where['member_id'] = ['eq',$user_info['id']];
        $prize = $lotteryOrder->selectJoinInfo($where,'b.id,b.name,code');
        $row = $redis->get('lottery_user:' . date('Y-m-d') . $user_info['id']);
        $result = Config::get('code.success');
        $result['prize'] = $prize;
        if($row === false){
            $row = 3;
        }
        $forward = $redis->get('forward:' . date('Y-m-d', time()) . "/" . $user_info['id'] );
        if($forward !== false){
            $result['forward'] = 0;
        }else{
            $result['forward'] = 1;
        }
        $result['num'] = $row;
        return json($result);
    }

    /*
     * 抽奖动作（算法）
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return json
     */
    public function lottery($prize_arr){
        foreach ($prize_arr as $key => $val) {
            $arr[$val['id']] = $val['v'];
        }
        $rid = $this->get_rand($arr); //根据概率获取奖项id
        return $rid;
    }

    public function get_rand($proArr) {
        $result = '';
        $proSum = array_sum($proArr);
        foreach ($proArr as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($proArr);
        return $result;
    }

    /**
     * 下载中奖excel
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function getPrizeExcel(Request $request,LotteryOrder $lotteryOrder){
        $param = $request->param();
        if(empty($param['token'])){
            return json(Config::get('code.mistake'));
        }
        if($param['token'] != sha1(md5('hry123456cpy'))){
            return json(Config::get('code.pwdError'));
        }
        $tableHeader = ['手机号','礼品名称','中奖识别码','活动批次','中奖时间'];
        $res = $lotteryOrder->selectJoinInfo(['a.batch' => 4],'mobile,b.name,code,a.batch,a.create_time');
        $data = [];
        foreach($res as $k=>$v){
            $data[$k]['mobile'] =  $v['mobile'];
            $data[$k]['name'] =  $v['name'];
            $data[$k]['code'] =  $v['code'];
            $data[$k]['batch'] =  $v['batch'];
            $data[$k]['create_time'] =  $v['create_time'];
        }
        ToGetEXECL($tableHeader,$data,'中奖列表');
    }

    /**
     * @return Request
     */
    public function getUserDetail(Request $request)
    {
        $redis = Redis::instance();
        $param = $request->param();
        if($param['type'] == 'vip'){
            $name = '成功登录vip名单';
            $row = $redis->keys('lottery_vip:2020-01-25*');
            $row1 = $redis->keys('lottery_vip:2020-01-26*');
            $row2 = $redis->keys('lottery_vip:2020-01-27*');
            $row3 = $redis->keys('lottery_vip:2020-01-28*');
            $row4 = $redis->keys('lottery_vip:2020-01-29*');
            $row5 = $redis->keys('lottery_vip:2020-01-30*');
            $row6 = $redis->keys('lottery_vip:2020-01-31*');
        }elseif ($param['type'] == 'no_vip'){
            $name = '成功登录非vip名单';
            $row = $redis->keys('lottery_no_vip:2020-01-25*');
            $row1 = $redis->keys('lottery_no_vip:2020-01-26*');
            $row2 = $redis->keys('lottery_no_vip:2020-01-27*');
            $row3 = $redis->keys('lottery_no_vip:2020-01-28*');
            $row4 = $redis->keys('lottery_no_vip:2020-01-29*');
            $row5 = $redis->keys('lottery_no_vip:2020-01-30*');
            $row6 = $redis->keys('lottery_no_vip:2020-01-31*');
        }
        $res = array_merge($row,$row1,$row2,$row3,$row4,$row5,$row6);
        foreach ($res as $k => $v){
            $rat = $redis->get($v);
            $rat = explode("/",$rat);
            $res[$k] = $rat;
            //$res[] = substr($v,23,10);
        }
        foreach ($res as $k => $v){
            $info[$k] = Db::table('tf_member')->field('mobile,username')->where('id',$v[0])->find();
            $info[$k]['login_time'] = $v[1];
        }
        $tableHeader = ['手机号','姓名','登录时间'];
        $data = [];
        foreach($info as $k=>$v){
            if($v){
                $data[$k]['mobile'] =  $v['mobile'];
                $data[$k]['username'] =  $v['username'];
                $data[$k]['login_time'] =  $v['login_time'];
            }
        }
        ToGetEXECL($tableHeader,$data,$name);
    }

    /**
     * 首页
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function index(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        $money = $redis->get('lottery_user_money:' . $user_info['id']);
        $bet = $redis->get('lottery_user_bet:' . $user_info['id']);
        $answer = $redis->get('lottery_answer:'.date('Y-m-d').$user_info['id']);
        if($answer == 10){
            $answerNum = 1;
        }elseif ($answer == 30){
            $answerNum = 2;
        }elseif ($answer == 60){
            $answerNum = 3;
        }elseif ($answer == 100){
            $answerNum = 4;
        }elseif ($answer == 150){
            $answerNum = 5;
        }else{
            $answerNum = 0;
        }
        $num = $this->getNoticeList($user_info);
        $isFirst = $this->lotteryNewYear($user_info['id'],$user_info['is_vip']);
        if($user_info['is_vip'] == 1 && !empty($isFirst)){
            $isAdd = 1;
        }else{
            $isAdd = 0;
        }

        $result = Config::get('code.success');
        $result['id'] = $user_info['id'];
        $result['head_thumb'] = $user_info['head_thumb'];
        $result['username'] = $user_info['username'];
        $result['is_vip'] = $user_info['is_vip'];
        $result['money'] = empty($money)?0:$money;
        $result['bet'] = empty($bet)?0:1;
        $result['bet_num'] = $bet;
        $result['answer'] = empty($answer)?0:1;
        $result['answer_num'] = $answerNum;
        $result['num'] = $num['num'];
        $result['is_add'] = $isAdd;
        return json($result);
    }

    /**
     * 积分记录
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function intLog(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        $money = $redis->get('lottery_user_money:' . $user_info['id']);

        $answer1 = $redis->get('lottery_answer:'.date($this->day1).$user_info['id']);
        $answer2 = $redis->get('lottery_answer:'.date($this->day2).$user_info['id']);
        $answer3 = $redis->get('lottery_answer:'.date($this->day3).$user_info['id']);
        $answer4 = $redis->get('lottery_answer:'.date($this->day4).$user_info['id']);
        $answer5 = $redis->get('lottery_answer:'.date($this->day5).$user_info['id']);
        $answer6 = $redis->get('lottery_answer:'.date($this->day6).$user_info['id']);
        $answer7 = $redis->get('lottery_answer:'.date($this->day7).$user_info['id']);

        $sign1 = $redis->get('lottery_sign:'.date($this->day1).$user_info['id']);
        $sign2 = $redis->get('lottery_sign:'.date($this->day2).$user_info['id']);
        $sign3 = $redis->get('lottery_sign:'.date($this->day3).$user_info['id']);
        $sign4 = $redis->get('lottery_sign:'.date($this->day4).$user_info['id']);
        $sign5 = $redis->get('lottery_sign:'.date($this->day5).$user_info['id']);
        $sign6 = $redis->get('lottery_sign:'.date($this->day6).$user_info['id']);
        $sign7 = $redis->get('lottery_sign:'.date($this->day7).$user_info['id']);

        $vipTime = $redis->get('lottery_vip_user_login_time:'. $user_info['id']);
        $vip = $redis->get('lottery_vip_user_login:'. $user_info['id']);

        $data[0]['sign'] = empty($sign1)?0:$sign1;
        $data[1]['sign'] = empty($sign2)?0:$sign2;
        $data[2]['sign'] = empty($sign3)?0:$sign3;
        $data[3]['sign'] = empty($sign4)?0:$sign4;
        $data[4]['sign'] = empty($sign5)?0:$sign5;
        $data[5]['sign'] = empty($sign6)?0:$sign6;
        $data[6]['sign'] = empty($sign7)?0:$sign7;

        $data[0]['answer'] = empty($answer1)?0:$answer1;
        $data[1]['answer'] = empty($answer2)?0:$answer2;
        $data[2]['answer'] = empty($answer3)?0:$answer3;
        $data[3]['answer'] = empty($answer4)?0:$answer4;
        $data[4]['answer'] = empty($answer5)?0:$answer5;
        $data[5]['answer'] = empty($answer6)?0:$answer6;
        $data[6]['answer'] = empty($answer7)?0:$answer7;

        $data[0]['time'] = date($this->day1);
        $data[1]['time'] = date($this->day2);
        $data[2]['time'] = date($this->day3);
        $data[3]['time'] = date($this->day4);
        $data[4]['time'] = date($this->day5);
        $data[5]['time'] = date($this->day6);
        $data[6]['time'] = date($this->day7);
        $data[7]['time'] = date('2020-02-01');

        $vipTime = date('Y-m-d',strtotime($vipTime));
        if($vipTime == date($this->day1)){
            $data[0]['vip'] = $vip;
        }elseif ($vipTime == date($this->day2)){
            $data[1]['vip'] = $vip;
        }elseif ($vipTime == date($this->day3)){
            $data[2]['vip'] = $vip;
        }elseif ($vipTime == date($this->day4)){
            $data[3]['vip'] = $vip;
        }elseif ($vipTime == date($this->day5)){
            $data[4]['vip'] = $vip;
        }elseif ($vipTime == date($this->day6)){
            $data[5]['vip'] = $vip;
        }elseif ($vipTime == date($this->day7)){
            $data[6]['vip'] = $vip;
        }

        $bet = $redis->get('lottery_user_bet:' . $user_info['id']);
        if($bet == $this->betResult){
            $betRe = 500;
        }else{
            $betRe = 0;
        }
        $data[7]['bet'] = $betRe;

        $result = Config::get('code.success');
        $result['data'] = $data;
        $result['all'] = empty($money)?0:$money;
        return json($result);
    }

    /**
     * 押宝
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function bet(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $param = $request->param();
        $user_info = $request->lottery_user_info;

        if(time() > strtotime(date('2020-01-25 0:0:0'))){
            abort(json([
                'msg' => '待开奖!',
                'status' => 211
            ]));
        }
        if(empty($param['bet'])){
            $result = Config::get('code.mistake');
            return json($result);
        }
        $param['bet'] = intval($param['bet']);

        $row = $redis->get('lottery_user_bet:' . $user_info['id']);
        if($row === false){
            $redis->set('lottery_user_bet:' . $user_info['id'],$param['bet']);
        }
        $result = Config::get('code.success');
        return json($result);
    }

    /**
     * 押宝结果
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function betResult(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        if(time() < strtotime(date('2020-02-01 10:00:00'))){
            $result = Config::get('code.error');
            $result['msg'] = '尚未开奖，敬请期待';
            return json($result);
        }

        $bet = $this->betResult;
        $row = $redis->get('lottery_user_bet:' . $user_info['id']);
        if($row == $bet){
            $isBet = 1;
//            if($rad === false){
//                $money = $redis->get('lottery_user_money:' . $user_info['id']);
//                $redis->set('lottery_user_money:' . $user_info['id'], $money+500);
//            }
        }else{
            $isBet = 0;
        }
        $result = Config::get('code.success');
        $result['is_bet'] = $isBet;
        $result['bet'] = $row;
        return json($result);
    }

    /**
     * 押宝执行
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function betAdd(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        $money = $redis->get('lottery_user_money:' . $user_info['id']);
        $rat = $redis->get('lottery_user_bet_add:'.$user_info['id']);
        halt($rat);

        $row = $redis->keys('lottery_user_bet:*');
        foreach ($row as $k=>$v){
            $rat = $redis->get($v);
            $id = explode(':',$v);
            if($rat == $this->betResult){
                $sure = $redis->get('lottery_user_bet_add:'.$id[1]);
                if($sure === false){
                    $money = $redis->get('lottery_user_money:' . $id[1]);
                    $redis->set('lottery_user_money:' . $id[1], $money+500);
                    $redis->set('lottery_user_bet_add:'.$id[1],500);
                }
            }
        }
        $result = Config::get('code.success');
        return json($result);
    }

/**
     * 执行30积分（所有用户）
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function getAdd(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;
		halt('no');
        $row = $redis->keys('lottery_user_money:*');
        foreach ($row as $k=>$v){
            $rat = $redis->get($v);
            $redis->set($v, $rat+30);
        }
        $result = Config::get('code.success');
        return json($result);
    }

    /**
     * 签到列表
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function signList(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        if(time() > strtotime(date($this->day1.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day1).$user_info['id']))){
            $one = 2;
        }else{
            $one = empty($redis->get('lottery_sign:'.date($this->day1).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day2.' 22:0:0')) && empty($redis->get('lottery_sign:'.date('2020-01-26').$user_info['id']))){
            $two = 2;
        }else{
            $two = empty($redis->get('lottery_sign:'.date($this->day2).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day3.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day3).$user_info['id']))){
            $three = 2;
        }else{
            $three = empty($redis->get('lottery_sign:'.date($this->day3).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day4.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day4).$user_info['id']))){
            $four = 2;
        }else{
            $four = empty($redis->get('lottery_sign:'.date($this->day4).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day5.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day5).$user_info['id']))){
            $five = 2;
        }else{
            $five = empty($redis->get('lottery_sign:'.date($this->day5).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day6.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day6).$user_info['id']))){
            $six = 2;
        }else{
            $six = empty($redis->get('lottery_sign:'.date($this->day6).$user_info['id']))?0:1;
        }
        if(time() > strtotime(date($this->day7.' 22:0:0')) && empty($redis->get('lottery_sign:'.date($this->day7).$user_info['id']))){
            $seven = 2;
        }else{
            $seven = empty($redis->get('lottery_sign:'.date($this->day7).$user_info['id']))?0:1;
        }

        $res['one'] = $one;
        $res['two'] = $two;
        $res['three'] = $three;
        $res['four'] = $four;
        $res['five'] = $five;
        $res['six'] = $six;
        $res['seven'] = $seven;

        $num = $redis->get('lottery_sign_num:'.$user_info['id']);

        $result = Config::get('code.success');
        $result['list'] = $res;
        $result['all'] = empty($num)?0:$num;
        return $result;
    }

    /**
     * 签到
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function sign(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        if(time() < strtotime(date('2020-01-25 0:0:0'))){
        //if(time() < strtotime(date('2020-01-15 0:0:0'))){
            $result = Config::get('code.error');
            $result['msg'] = '活动尚未结束，敬请期待';
        }elseif(time() > strtotime(date('2020-01-25 0:0:0')) && time() < strtotime(date('2020-01-31 23:59:55'))){
        //}elseif(time() > strtotime(date('2020-01-15 0:0:0')) && time() < strtotime(date('2020-01-31 23:59:55'))){
            if ($user_info['is_vip'] == 2 && time() > strtotime(date('2020-01-26 23:59:55'))) {
                $result = Config::get('code.error');
                $result['msg'] = '您不是VIP会员，最多只可签到两天';
                return json($result);
            }
            $row = $redis->get('lottery_sign:'.date('Y-m-d').$user_info['id']);
            if($row === false){
                $num = $redis->get('lottery_sign_num:'.$user_info['id']);
                if($num === false){
                    $redis->set('lottery_sign_num:',0);
                    $num = $redis->get('lottery_sign_num:'.$user_info['id']);
                }
                $redis->set('lottery_sign_num:'.$user_info['id'],$num+1);
                if($num+1 == 7){
                    $money = $redis->get('lottery_user_money:' . $user_info['id']);
                    $redis->set('lottery_user_money:' . $user_info['id'], $money+250);
                    $redis->set('lottery_sign:'.date('Y-m-d').$user_info['id'],250);
                    $result = Config::get('code.success');
                    $result['msg'] = '恭喜您，已签到满7天，再奖励200福鼠';
                }else{
                    $money = $redis->get('lottery_user_money:' . $user_info['id']);
                    $redis->set('lottery_user_money:' . $user_info['id'], $money+50);
                    $redis->set('lottery_sign:'.date('Y-m-d').$user_info['id'],50);
                    $result = Config::get('code.success');
                }
            }else{
                $result = Config::get('code.error');
                $result['msg'] = '您今日已签到';
            }
        }else{
            $result = Config::get('code.error');
            $result['msg'] = '活动已结束，感谢您的参与';
        }
        return json($result);
    }

    /**
     * 答题
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function answer(Request $request)
    {
        $redis = Redis::instance();
        $this->beforeLottery();
        $param = $request->param();
        $user_info = $request->lottery_user_info;

        if(time() < strtotime(date('2020-01-25 0:0:0'))){
            $result = Config::get('code.error');
            $result['msg'] = '答题还未开始';
            return json($result);
        }
        if(time() > strtotime(date('Y-m-d 23:55:0'))){
            $result = Config::get('code.error');
            $result['msg'] = '今日答题已结束';
            return json($result);
        }
        if(time() < strtotime(date('Y-m-d 10:0:0'))){
            $result = Config::get('code.error');
            $result['msg'] = '今日答题尚未开始';
            return json($result);
        }
        if(time() > strtotime(date('2020-01-31 23:55:0'))){
            $result = Config::get('code.error');
            $result['msg'] = '答题活动已结束';
            return json($result);
        }
        $param['num'] = intval($param['num']);

        $row = $redis->get('lottery_answer:'.date('Y-m-d').$user_info['id']);
        if($row === false){
            if($param['num'] == 1){
                $money = 10;
            }elseif($param['num'] == 2){
                $money = 30;
            }elseif($param['num'] == 3){
                $money = 60;
            }elseif($param['num'] == 4){
                $money = 100;
            }elseif($param['num'] == 5){
                $money = 150;
            }else{
                $money = 0;
            }
            $all = $redis->get('lottery_user_money:' . $user_info['id']);
            $redis->set('lottery_user_money:' . $user_info['id'], $money + $all);
            $redis->set('lottery_answer:'.date('Y-m-d').$user_info['id'],$money);
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.error');
            $result['msg'] = '您今日已答题';
        }
        return json($result);
    }
	
	/**
     * 排行下载
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function noticeListDownload(Request $request)
    {
        $data = $this->getNoticeList($user_info);
		foreach ($data['list'] as $k => $v){
            if($k > 19){
                break;
            }else{
				unset($v['create_time']);
                $res[$k] = $v;
            }
        }
		
		$name = '排行名单';
		$tableHeader = ['id','姓名','头像','电话','订单金额','福鼠'];
        $data = $res;
//        foreach($res as $k=>$v){
//            if($v){
//                $data[$k]['mobile'] =  $v['mobile'];
//                $data[$k]['username'] =  $v['username'];
//                $data[$k]['login_time'] =  $v['login_time'];
//            }
//        }
        ToGetEXECL($tableHeader,$data,$name);
    }

    /**
     * 排行
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function noticeList(Request $request)
    {
        $this->beforeLottery();
        $user_info = $request->lottery_user_info;

        $result = Config::get('code.success');
        $data = $this->getNoticeList($user_info);
        foreach ($data['list'] as $k => $v){
            if($k > 19){
                break;
            }else{
                $res[$k] = $v;
            }
        }
        $data['list'] = $res;
        $result['data'] = $data;
        return json($result);
    }

    /**
     * 排行
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    private function getNoticeList($user_info){
        $redis = Redis::instance();
        $order = new Order();
        $row = $redis->keys('lottery_user_money:*');
        foreach ($row as $k => $v){
            $rat = $redis->get($v);
            $id = explode(':',$v);
            $user = Db::table('tf_member')->where('id',$id[1])->find();
            $where['uid'] = ['eq', $id[1]];
            $where['status'] = ['>', 1];
            $orderMoney = $order->selectInfo($where,'sum(money)');
            $res[$k]['id'] = $id[1];
            $res[$k]['name'] = starReplace($user['username']);
            //$res[$k]['name'] = $user['username'];
            $res[$k]['head_thumb'] = $user['head_thumb'];
            $res[$k]['mobile'] = maskMobile($user['mobile']);
            //$res[$k]['mobile'] = $user['mobile'];
            $res[$k]['order_money'] = $orderMoney[0]['sum(money)'];
            $res[$k]['money'] = $rat;
            $res[$k]['create_time'] = $user['create_time'];
        }

        $money =  array_column( $res, 'money');
        $order =  array_column( $res, 'order_money');
        $createTime =  array_column( $res, 'create_time');

        array_multisort($money,SORT_NUMERIC,SORT_DESC,$order,SORT_NUMERIC,SORT_DESC,$createTime,SORT_NUMERIC,SORT_ASC,$res);

        $id =  array_column( $res, 'id');
        $num = array_search($user_info['id'],$id);
        if($num === false){
            $num = count($res);
        }

        $result['list'] = $res;
        $result['num'] = $num+1;
        return $result;
    }

    /**
     * 退出
     * @param Request $request
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function loginOut(Request $request, Member $user)
    {
        $user_info = $request->user_info;
        $redis = Redis::instance();
        $res = $redis->hDel('user_info', $user_info['front_token']);
        if($res){
            Session::delete('user_id');
            $result = Config::get('code.success');
        }else{
            $result = Config::get('code.error');
        }
        return json($result);
    }

    public function getJsApiTicket(Request $request){
        $param = $request->param();
//        $this->beforeLottery();
        $res = $this->getAccessToken($this->appId,$this->appSecret);
        $geturl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$res;

        //$url = 'http://gift.hrycf.com';
        $url = urldecode($param['url']);
        $ticket = json_decode($this->curl_get($geturl),true);
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=".$ticket['ticket']."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
        $signature = sha1($string);

        $result = Config::get('code.success');
        $result['appId'] = $this->appId;
        $result['nonceStr'] = $nonceStr;
        $result['timestamp'] = $timestamp;
        $result['url'] = $url;
        $result['signature'] = $signature;
        $result['rawString'] = $string;
        //如果是接口，这里则是 echo json_encode($signPackage);
        return $result;
    }

    public function getAccessToken($appid,$secret){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
        $res = $this->curl_get($url);
        $res = json_decode($res,1);
        if($res['errcode']!=0) {
            echo $res['errmsg'];die;
//            throw new Exception($res['errmsg']);
        }
        return $res['access_token'];
    }

    public function curl_get($url) {
        $headers = array('User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36');
        $oCurl = curl_init();
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_TIMEOUT, 20);
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if(intval($aStatus["http_code"])==200){
            return $sContent;
        }else{
            return false;
        }
    }

    // 创建获取随机字符串
    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }



    /**
     * 记录浏览数值
     * @return \think\response\Json
     * @author cpy(1442435897@qq.com)
     */
    public function countData()
    {
        $path = BASE_PATH.'application/wap/countLog.txt';
        $data=intval(file_get_contents($path));
        $data+=1;
        file_put_contents($path,$data);
        $result = Config::get('code.success');
        return json($result);
    }




}